package io.lkt.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import io.lkt.common.config.AliyunOSSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Component
public class AliyunOssClientUtil {

    @Autowired
    private AliyunOSSConfig aliyunOSSConfig;

    public static AliyunOssClientUtil aliyunOssClientUtil;

    public static String ossImgUrl="zktfile.wxslzf.com";

    @PostConstruct
    public void init() {
        aliyunOssClientUtil = this;
    }

    /**
     * 获取OSSClient实例
     *
     * @return
     */
    private static OSS getOSSClient() {
        OSS ossClient = new OSSClient(aliyunOssClientUtil.aliyunOSSConfig.getEndpoint(), aliyunOssClientUtil.aliyunOSSConfig.getAccessKeyId(), aliyunOssClientUtil.aliyunOSSConfig.getAccessKeySecret());
        return ossClient;
    }

    /**
     * 上传用户二维码图片
     *
     * @param file
     * @param key
     * @return
     * @throws IOException
     */
    public static String uploadFileByMultipartFile(MultipartFile file, String key) throws IOException {
        getOSSClient().putObject(aliyunOssClientUtil.aliyunOSSConfig.getBucketName(), key, file.getInputStream());
        getOSSClient().shutdown();
        return key;
    }

    //文件流上传
    public static void uploadFileByLocalFile(File file, String key) {
        getOSSClient().putObject(aliyunOssClientUtil.aliyunOSSConfig.getBucketName(), key, file);
        getOSSClient().shutdown();
    }

    /**
     * 网络URL上传
     *
     * @param dataSrc
     * @param key
     */
    public static void uploadFileByUrl(String dataSrc, String key) {
        InputStream inStream = null;
        try {
            HttpURLConnection webConn = null;
            //获取视频链接
            URL webUrl = new URL(dataSrc);
            //打开链接
            webConn = (HttpURLConnection) webUrl.openConnection();
            //设置请求方式为"GET"
            webConn.setRequestMethod("GET");
            //建立连接的超时时间
            webConn.setConnectTimeout(10 * 1000);
            //传递数据的超时时间
            webConn.setReadTimeout(10 * 1000);
            //通过输入流获取数据
            inStream = webConn.getInputStream();

            getOSSClient().putObject(aliyunOssClientUtil.aliyunOSSConfig.getBucketName(), key, inStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            getOSSClient().shutdown();// 关闭OSSClient。
        }
    }

    //URL上传
    public static void uploadFileByFileUrl(String fileUrl, String key) {
        // 上传网络流。
        InputStream inputStream = null;
        try {
            inputStream = new URL(fileUrl).openStream();

            getOSSClient().putObject(aliyunOssClientUtil.aliyunOSSConfig.getBucketName(), key, inputStream);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // 关闭OSSClient。
        getOSSClient().shutdown();
    }

    public static String uploadFileByFileUrl2(String urlStr) {
        String ossImgUrl = "";
        HttpURLConnection connection = null;
        URL url = null;
        String suffix = null;

        try {
            url = new URL(urlStr);

            connection = (HttpURLConnection) url.openConnection();

            connection.setInstanceFollowRedirects(true);
            connection.setUseCaches(true);

            suffix = MIMEType.getSuffix(connection.getContentType());
            String strDate = DateUtil.getFormatDate("yyyyMMdd", new Date());
            String filePath = "ps/" + strDate + "/" + UUID.randomUUID() + suffix;
            uploadFileByFileUrl(urlStr, filePath);
            ossImgUrl = "http://zktfile.wxslzf.com/" + filePath;

        } catch (Exception e) {
            ossImgUrl = urlStr;
        }
        return ossImgUrl;
    }

    /**
     * 删除文件
     * objectName key 地址
     *
     * @param filePath
     */
    public static Boolean delFile(String filePath) {
        // 创建OSSClient实例。
        OSS ossClient = getOSSClient();
        try {

            // 删除Object.
            boolean exist = ossClient.doesObjectExist(aliyunOssClientUtil.aliyunOSSConfig.getBucketName(), filePath);
            if (!exist) {
                return false;
            }
            ossClient.deleteObject(aliyunOssClientUtil.aliyunOSSConfig.getBucketName(), filePath);
        } catch (Exception e) {
            System.out.println("AliyunOss delFile:" + e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return true;
    }

    /**
     * 批量删除
     *
     * @param keys
     */
//    public Boolean delFileList(List<String> keys) {
//        // 创建OSSClient实例。
//        OSS ossClient = getOSSClient();
//        try {
//            // 删除文件。
//            DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));
//            List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
//        } catch (Exception e) {
//            e.printStackTrace();
//            return false;
//        } finally {
//            ossClient.shutdown();
//        }
//        return true;
//
//    }
}
